<?php

namespace app\common\util\plug;

use app\common\util\base\BaseObserver;
use app\common\util\base\BaseServer;
use sffi\recovery\Factory;
use think\Exception;

class PlugCreateTable extends BaseObserver
{

    public function handle()
    {
        $path = $this->server->getPlugTempPath();
        $plugInfo = $this->server->getPlugInfo();
        if (!$plugInfo['tables']) {
            return true;
        }
        $tablesFile = $path.$plugInfo['tables'];
        $types = [
            '.php'   => 'parseArray',
            '.json'  => 'parseJson',
            '.yaml'  => 'parseYaml',
            '.sql'   => 'parseMysql'
        ];
        $method = '';
        foreach ($types as $key => $func) {
            if (strpos($plugInfo['tables'], $key)) {
                $method = $func;
            }
        }
        if (!$method) throw new Exception('错误的配置文件');
        if (is_file($tablesFile)){
            $tables = require $tablesFile;
            $config = config('database.connections');
            $dbConfig = $config[config('database.default')];
            Factory::$method($tables, $dbConfig)->exe();
        }
        trace('插件数据库已完成创建');
        return true;
    }
}